<script setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { getForumArticleCommentListService } from '@/api/forumComment';
import { useUserInfoStore } from '@/store/userInfo';
import { doCommentLikeService, changeCommentTopTypeService } from '@/api/forumComment';
import PostComment from '@/components/PostComment.vue';
import CommentImage from '@/components/CommentImage.vue';
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 用户信息store
const userInfoStore = useUserInfoStore()

// 获取父级传递过来的文章ID
let props = defineProps({
  forumArticle: {
    type: Object,
    default: {}
  },
})

// 是否显示加载框
const loading = ref(null)

// 评论
const forumCommentList = ref([])
// 评论数
const forumCommentTotal = ref(0)

// 评论搜索条件
const forumCommentCondition = ref({
  articleId: '',
  orderType: 0,
  pageNum: 1,
  pageSize: 10,
})

// 分页
const handleCurrentChange = (val) => {
  forumCommentCondition.value.pageNum = val
  getForumCommentList()
}

// 获取文章相关评论
const getForumCommentList = async () => {
  // 准备评论搜索条件
  forumCommentCondition.value.articleId = props.forumArticle.articleId

  // 显示加载框
  loading.value = true

  // 发送请求
  let result = await getForumArticleCommentListService(forumCommentCondition.value);

  // 关闭加载框
  loading.value = false

  // 得到 文章评论 和 评论数
  forumCommentList.value = result.data.forumCommentList
  forumCommentTotal.value = result.data.total

  // 为每一条评论添加一个属性（是否显示回复框），显示评论框前，需将之前显示的所有评论框隐藏
  if (forumCommentList.value != null) {
    forumCommentList.value.forEach((element, index) => {
      element.showReply = false
      if (element.children) {
        element.children.forEach((i) => {
          i.showReply = false
        })
      }
    })
  }
}

// 修改文章评论的排序方式
const changeCommentOrderType = (type) => {
  forumCommentCondition.value.orderType = type
  getForumCommentList()  // 获取文章评论
}


// 显示评论框(一级 或 二级)
const chooseCommentData = ref() // 当前选中的评论
const parentCommentIndex = ref() // 当前评论的父级下标（无论一级评论或二级评论）
const showReplyPanel = (currentData, pindex, parentData) => {

  // 当前选中的评论
  chooseCommentData.value = currentData

  // 先清空需要用到的下标
  parentCommentIndex.value = pindex

  // 状态缓存
  // 由于这里的currentData可能为一级评论，也可能为二级评论，所以就集中统一处理了
  const tmp = parentData.showReply

  // 显示评论框前，需将之前显示的所有评论框隐藏
  forumCommentList.value.forEach((element) => {
    element.showReply = false
    if (element.children) {
      element.children.forEach((i) => {
        i.showReply = false
      })
    }
  })

  // 再将当前选中的评论框显示
  parentData.showReply = !tmp

  // 若点击的是二级评论，则不隐藏发表评论框
  if (currentData.commentId != parentData.commentId) {
    parentData.showReply = true
  }
}

// 父组件方法
const emit = defineEmits(['parentChangeCommentCount']);

// 发表评论完成的回调函数
const postCommentFinish = (resultData, commentType) => {
  if (commentType == 0) {
    // 发表的对文章的评论
    if (forumCommentList.value == null) {
      // 本文的第一条评论
      forumCommentList.value = []
    }
    forumCommentList.value.unshift(resultData)

    // 文章评论数+1
    forumCommentTotal.value = forumCommentTotal.value + 1

    // 父级：修改评论数
    emit('parentChangeCommentCount');

  } else if (commentType == 1) {
    // 回复一级评论（有可能一级评论的二级评论为null）
    if (forumCommentList.value[parentCommentIndex.value].children == null) {
      forumCommentList.value[parentCommentIndex.value].children = []
    }
    forumCommentList.value[parentCommentIndex.value].children.push(resultData)
  }
}

// 评论点赞
const doCommentLike = async (item, index, childIndex) => {
  let result = await doCommentLikeService({
    commentId: item.commentId
  })

  let tmpCount = 1
  if (result.data.likeType == 0) {
    // 取消点赞
    tmpCount = -1
  }

  // 判断是1级评论还是2级评论
  if (childIndex == null) {
    // 一级评论
    forumCommentList.value[index].likeCount = forumCommentList.value[index].likeCount + tmpCount
    forumCommentList.value[index].likeType == null ? forumCommentList.value[index].likeType = 1 : forumCommentList.value[index].likeType = forumCommentList.value[index].likeType + tmpCount
  } else {
    // 二级评论
    forumCommentList.value[index].children[childIndex].likeCount = forumCommentList.value[index].children[childIndex].likeCount + tmpCount
    forumCommentList.value[index].children[childIndex].likeType == null ? forumCommentList.value[index].children[childIndex].likeType = 1 : forumCommentList.value[index].children[childIndex].likeType = forumCommentList.value[index].children[childIndex].likeType + tmpCount
  }

}

// 评论置顶/取消置顶
const changeCommentTopType = async (item, index) => {
  let result = await changeCommentTopTypeService({
    commentId: item.commentId
  })
  getForumCommentList()
}

// 跳转到用户中心页
const gotoUserCenter = (userId) => {
  router.push(`/userCenter/${userId}`)
}

onMounted(() => {
  getForumCommentList()  // 获取文章评论
})
</script>

<template>
  <!-- 用户评论 -->
  <div class="article-comment" id="article-comment">
    <div class="comment-panel">
      <!-- 排序 -->
      <div class="top-banner">
        <div class="title">评论<span class="count">{{ forumCommentTotal }}</span></div>
        <div class="tab">
          <div :class="[forumCommentCondition.orderType == 0 ? 'active' : '']" @click="changeCommentOrderType(0)">热榜
          </div>
          <el-divider direction="vertical" />
          <div :class="[forumCommentCondition.orderType == 1 ? 'active' : '']" @click="changeCommentOrderType(1)">最新
          </div>
        </div>
      </div>

      <!-- 发表评论 -->
      <PostComment :commentType="0" :showInsertImg="userInfoStore.userInfo != null" :forumArticle="forumArticle"
        @postCommentFinish="postCommentFinish">
      </PostComment>

      <!-- 评论列表 -->
      <div v-loading="loading" v-if="forumCommentList != null">
        <div class="comment-list" v-for="(item, index) in forumCommentList">
          <!-- 用户头像 -->
          <div class="avatar" @click="gotoUserCenter(item.userId)">
            <img v-if="item.avatar" :src="item.avatar" alt="">
            <img v-else src="../../assets/default_avatar.jpg" alt="">
            <!-- <img src="https://tse4-mm.cn.bing.net/th/id/OIP-C.jHUH4s7TQ48X_B-1iozuJgHaHa?rs=1&pid=ImgDetMain" alt=""> -->
          </div>
          <div class="right">
            <!-- 用户昵称 -->
            <span class="nickname" @click="gotoUserCenter(item.userId)">{{ item.nickname }}</span>
            <span class="tag-author" v-if="forumArticle.userId == item.userId">作者</span>
            <!-- 评论内容 -->
            <div class="comment-content">
              <div>
                <!-- 是否置顶 -->
                <!-- <span v-if="item.topType == 1" type="success" effect="plain" class="tag-top">置顶</span> -->
                <el-tag v-if="item.topType == 1" type="success" effect="plain" class="tag-top">置顶</el-tag>
                <span v-html="item.content" style="line-height: 24px;"></span>
              </div>
              <!-- 评论中携带的图片 -->
              <CommentImage :style="{ 'margin-top': '10px' }" v-if="item.imgPath" :src="item.imgPath">
              </CommentImage>
            </div>
            <!-- 其他内容 -->
            <div class="other-detail">
              <span>{{ item.postTime }}</span>
              <span @click="doCommentLike(item, index, null)" style="cursor: pointer;">
                <span :class="['iconfont icon-dianzan_kuai', item.likeType == 1 ? 'active' : '',]"></span>
                <span class="do-like">{{ item.likeCount > 0 ? item.likeCount : "点赞" }}</span>
              </span>
              <span @click="showReplyPanel(item, index, item)" style="cursor: pointer;">
                <span class="iconfont icon-pinglun"></span>
                <span>回复</span>
              </span>
              <!-- （若为文章作者）取消置顶 -->
              <el-dropdown v-if="userInfoStore.userInfo.userId == item.userId">
                <span class="iconfont icon-moreandroid"></span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="changeCommentTopType(item, index)">{{ item.topType == 0 ? "设为置顶" : "取消置顶"
                    }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <!-- 二级评论 -->
            <div class="comment-sub-list" v-if="item.children">
              <div class="comment-sub-item" v-for="(child, childIndex) in item.children">
                <div class="avatar" @click="gotoUserCenter(child.userId)">
                  <img v-if="child.avatar" :src="child.avatar" alt="">
                  <img v-else src="../../assets/default_avatar.jpg" alt="">
                </div>
                <div class="right">
                  <div class="main">
                    <div class="nickname" @click="gotoUserCenter(child.userId)">{{ child.nickname }}</div>
                    <div class="tag-author" v-if="forumArticle.userId == child.userId">作者</div>
                    <div class="reply-name">回复 </div>
                    <div class="reply-nickname" @click="gotoUserCenter(child.replyUserId)">@{{ child.replyNickname
                    }}&nbsp;:</div>
                    <div class="comment-content" v-html="child.content"></div>
                  </div>
                  <div class="other-detail">
                    <span>{{ child.postTime }}</span>
                    <span @click="doCommentLike(child, index, childIndex)" style="cursor: pointer;">
                      <span :class="['iconfont icon-dianzan_kuai', child.likeType == 1 ? 'active' : '',]"></span>
                      <span class="do-like">{{ child.likeCount > 0 ? child.likeCount : "点赞" }}</span>
                    </span>
                    <span @click="showReplyPanel(child, index, item)" style="cursor: pointer;">
                      <span class="iconfont icon-pinglun"></span>
                      <span>回复</span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <!-- 回复评论 -->
            <!-- 因为每一个item中都没有showReply属性，所以都不显示 -->
            <div class="reply-panel" v-if="item.showReply">
              <PostComment :commentType="1" :forumArticle="forumArticle" :chooseComment="chooseCommentData"
                :placeholderInfo="`回复 @${chooseCommentData.nickname}`" :showInsertImg="false"
                @postCommentFinish="postCommentFinish">
              </PostComment>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="comment-pagination">
          <el-pagination background layout="prev, pager, next" :total="forumCommentTotal"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>

      <!-- 若无评论则显示空 -->
      <el-empty v-else :image-size="100" description="目前暂无评论，快来抢沙发吧"></el-empty>

    </div>
  </div>
</template>

<style scoped>
.article-comment .comment-panel {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px;
}

/* 排序 */
.article-comment .comment-panel .top-banner {
  display: flex;
  margin-bottom: 20px;
}

.article-comment .comment-panel .top-banner .title {
  font-size: 20px;
  font-weight: 400;
  margin-bottom: 0px;
}

.article-comment .comment-panel .top-banner .title .count {
  margin-left: 10px;
  font-size: 16px;
  margin-right: 20px;
  color: #9499A0;
}

.article-comment .comment-panel .top-banner .tab {
  display: flex;
  align-items: center;
  color: #9499A0;
}

.article-comment .comment-panel .top-banner .tab div {
  margin: 0 5px;
  line-height: 26px;
  cursor: pointer;
}

.article-comment .comment-panel .top-banner .tab div:hover {
  color: green;
}

.article-comment .comment-panel .top-banner .tab .active {
  color: #529b2e;
  font-weight: 700;
  border-bottom: 2px solid #529b2e;
}

/* 发表评论 */


/* 评论列表 */
.comment-list {
  display: flex;
  margin-top: 20px;
  font-size: 15px;
  color: #18191C;
}

/* 用户头像 */
.comment-list .avatar img {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  margin-right: 20px;
  background-color: #f0f0f0;
  text-align: center;
  line-height: 50px;
  font-size: 14px;
  cursor: pointer;
}

.comment-list .right {
  flex: 1;
  padding-bottom: 20px;
  border-bottom: 1px solid #ddd
}

/* 用户昵称 */
.comment-list .right .nickname {
  font-size: 15px;
  color: #555666;
  display: inline-block;
  margin-bottom: 8px;
  margin-right: 10px;
  cursor: pointer;
}

.comment-list .right .tag-author {
  background-color: green;
  color: #fff;
  font-size: 12px;
  border-radius: 3px;
  padding: 0 3px;
}

/* 评论内容 */
.comment-list .right .comment-content {
  font-size: 15px;
  color: #18191C;
  font-weight: 400;
}

/* 是否置顶 */
.comment-list .right .comment-content .tag-top {
  margin-right: 7px;
  padding: 0px 5px;
  cursor: default;
  text-align: center;
  font-size: 12px;
  border-radius: 4px;
  color: green;
  height: 20px;
  margin-bottom: 4px;
}

/* 其他内容 */
.comment-list .right .other-detail {
  margin-top: 8px;
  display: flex;
  align-items: center;
}

.comment-list .right .other-detail span {
  font-size: 13px;
  color: #9499A0;
  margin-right: 15px;
}

.comment-list .right .other-detail .iconfont {
  margin-right: 5px;
  cursor: pointer;
  /* 取消下拉框的边框 */
  outline: none;
}

.comment-list .right .other-detail .active {
  color: red;
}

/* 二级评论 */
.comment-list .right .comment-sub-list .comment-sub-item {
  display: flex;
  margin-top: 10px;
}

.comment-list .right .comment-sub-list .comment-sub-item .right {
  border-bottom: 0px solid #ddd;
  padding-bottom: 0px;
}

.comment-list .right .comment-sub-list .comment-sub-item .right .main {
  display: flex;
  align-items: center;
}

.comment-list .right .comment-sub-list .comment-sub-item .right .main .nickname {
  margin: 0px;
  margin-right: 5px;
}

.comment-list .right .comment-sub-list .comment-sub-item .right .main .tag-author {
  margin-right: 8px;
}

.comment-list .right .comment-sub-list .comment-sub-item .right .main .reply-name {
  margin-right: 8px;
}

.comment-list .right .comment-sub-list .comment-sub-item .right .main .reply-nickname {
  margin-right: 5px;
  cursor: pointer;
  color: #008AC5;
}

.comment-list .right .other-detail .comment-sub-list .comment-sub-item .right .other-detail .active {
  color: red;
}

/* 回复评论 */
.comment-list .right .reply-panel {
  margin-top: 20px;
}

/* 分页 */
.comment-pagination {
  margin-top: 10px;
}
</style>